"use strict"
/**
  启动web服务器的js文件
*/
//1.导入相应的包
const express=require("express");
const bodyParser=require("body-parser");
//2.创建app对象
const app=express();
const orm=require("orm");
const session=require("express-session");
//初始化session
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  // cookie: { secure: true }使用https协议时使用
  
}));
//post 获取参数
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json 
app.use(bodyParser.json())

//连接数据库
app.use(orm.express("mysql://root:hb921230124@127.0.0.1/data1",
	{define:(db,models,next)=>{
		console.log("连接数据库成功");
		models.user=db.define("login", {
			id:Number,
			name:String,
			pasw:String,
			status:Number
		});
		models.video=db.define("t-videoinfo", {
			vid:{ type: 'serial', key: true },
      vtitle:String,
      vsortno:Number,
      vvideoid:String,
      vsumary:String,
      vimgurl:String,
      vremark:String
		});
		next();	
	}
}))
//设置静态资源
app.use(express.static('./statics'));
//进行权限验证
app.all("/*",(req,res,next)=>{
	console.log(req.url);
	
	if(req.url.includes('login')||req.url.includes('jquery.min.js')||req.url.includes('bootstrap.min.css')||req.url.includes("vcode")||req.url.includes("/favicon.ico")){
		next();
		console.log("无需登录");
	}else{
		// 判断用户是否登录过,如果登陆过.就直接调用next()去访问真正的路由,
		// 如果没有登录/登录过期,跳到登录界面让用户去登录
		const name=req.session.name;
		if(name!=null){
			next();
		}else{
			res.setHeader("Content-Type","text/html;charset=utf-8");
	  res.end("<script>alert('请先登录!!!');window.location.href='/account/login';</script>");
		}	
		// next();
	}
});
//设置登录路由
const accountRouter=require("./routes/accountRoute.js");
app.use('/account',accountRouter);
//设置电影列表路由
const videoRoute=require("./routes/videoRoute.js");
app.use("/video",videoRoute);


app.listen(5566,"192.168.37.39",()=>{
	console.log("start server");
});